import * as md5 from 'md5'
import { RedisService } from 'src/redis/redis.service';
import { redisConnect } from './redis';

const redisService = new RedisService()
//生成token
export const MakeToken = (result) => {
    const token = md5(result.id + new Date().toLocaleString(), 16)
    const key = "adminId" + result.id + ":" + token
    redisService.setNS('token')
    redisService.set(key,result)
    return token;
}

//获取token
export const TakeToken = async (token, sn = 'default') => {
    const pattern = sn + '::' + sn + '*:' + token;
    const client = await (new redisConnect()).getInstance()
    const results = await client.keys(pattern)
    const str = results[0]
    if(str){
        return str.replace(sn + '::' + sn + ':','')
    }
    return ''
}

//清除此ID所有的token
export const ClearTokenById = async (id) => {
    const pattern = 'token::token:adminId' + id + ':*';
    const client = await (new redisConnect()).getInstance()
    const results = await client.keys(pattern)
    for(let i = 0; i < results.length; i++){
        client.del(results[i])
    }
    return results
}